﻿using System;
using System.Collections.Generic;
using System.Text;

namespace JoypadParser
{
    public static class Binary
    {
        public static byte[] CreatePacketBytes(int ax1, int ax2, int ax3, int ax4, int btns, int mnumber)
        {
            int len = 20;
            int package_type = len;
            byte[] p = new byte[len];
            p[0] = 0xFF;			//put the header information	
            p[1] = 0xFF;			//4 bytes	
            p[2] = 0xFF;			//Last byte defines the mask: 0xF0
            p[3] = 0xF2;

            p[4] = 0x00;                    //put the packet type informations (aligned with data size)
            p[5] = (byte)package_type;            //always 1 byte, filled with zeros to handle alignment

            p = Write2BValue(ax1, 6, p);
            p = Write2BValue(ax2, 8, p);
            p = Write2BValue(ax3, 10, p);
            p = Write2BValue(ax4, 12, p);
            p = Write2BValue(btns, 14, p);
            p = Write2BValue(mnumber, 16, p);

            p[18] = 0xff;
            p[19] = 0xff;
            return p;
        }

        public static byte[] Write2BValue(long val, int idx, byte[] p)
        {
            p[idx] = (byte)((val >> 8) & 0xff); //Prima + significativi, poi meno significativi
            if (((val >> 8) & 0xff) == 0xff)
            {
                p[idx + 1] = (byte)((val >> 0) & 0xef);
            }
            else
            {
                p[idx + 1] = (byte)((val >> 0));
            }
            return p;
        }
    }
}
